using System;
using System.ComponentModel;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
using SF.Code.Extension.HttpHelper.Downloader;
using SF.Code.Extension.HttpHelper.Mime;
using SG.Productivity.DesktopControlPanel.Support;

namespace SG.Productivity.DesktopControlPanel.ParallelQuery
{
    public class ProviderQueryConverter : Component, IWebDataConverter<QueryIdentifier, ProviderQueryResult, ProviderQueryResultEventArgs>
    {
        public ProviderQueryConverter()
            : this(null)
        {
            
        }

        public ProviderQueryConverter(IContainer container)
        {
            if (container != null)
                container.Add(this);
        }


        public ProviderQueryResult ToResult(byte[] bytes, ContentMetaData metaData)
        {
            var jsonString = metaData.GetString(bytes);
            // TODO: QueryResult ConvertDataToResult(byte[] bytes)
            var jsonData = JObject.Parse(jsonString);

            var key = (QueryIdentifier) jsonData;
            var record = (QueryRecord) jsonData;
            return ProviderQueryResult.Create(ref key, ref record);
        }

        public WebClient CreateWebClientPrototype()
        {
            var client = new WebClient {Encoding = Encoding.UTF8};
            client.Headers[HttpRequestHeader.Accept] = TypeSubPair.Json.ToString();
            return client;
        }

        public Uri KeyToUri(ref QueryIdentifier key)
        {
            var parameters = (StrongNameValueCollection)key;
            return parameters.ToUri(mainPart: Program.DefaultAddress, path: "search");
        }

        public ProviderQueryResultEventArgs CreateEventArgs(ProviderQueryResult result, bool fromCache)
        {
            return new ProviderQueryResultEventArgs(result, fromCache);
        }
    }
}